package com.shqcjd.yunweiyanoperator.ui.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.app.AppConstant;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.LoginBean;
import com.shqcjd.yunweiyanoperator.ui.activity.AdministerMainActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.CompanyActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.LoginActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.RegisterActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.staff.MainActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BaseFragment;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.AppManager;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.UIUtils;
import com.shqcjd.yunweiyanoperator.widget.LoginTipsDialog;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

public class PersonalRegisterFragment extends BaseFragment {


    @BindView(R.id.et_register_personal_phone)
    EditText etRegisterPersonalPhone;
    @BindView(R.id.tl_register_personal_phone)
    TextInputLayout tlRegisterPersonalPhone;
    @BindView(R.id.et_register_personal_pwd)
    EditText etRegisterPersonalPwd;
    @BindView(R.id.et_register_personal_pwd_true)
    EditText etRegisterPersonalPwdTrue;
    @BindView(R.id.tl_register_personal_pwd)
    TextInputLayout tlRegisterPersonalPwd;
    @BindView(R.id.tv_register_personal_next)
    TextView tvRegisterPersonalNext;
    @BindView(R.id.tv_register_personal_code)
    TextView tvRegisterPersonalCode;
    @BindView(R.id.et_register_personal_name)
    EditText etRegisterPersonalName;
    @BindView(R.id.et_register_personal_code)
    EditText etRegisterPersonalCode;
    @BindView(R.id.et_register_personal_info)
    EditText etRegisterPersonalInfo;
    @BindView(R.id.tv_register_personal_company)
    TextView tvRegisterPersonalCompany;
    @BindView(R.id.tl_register_personal_name)
    TextInputLayout tlRegisterPersonalName;
    @BindView(R.id.tl_register_personal_code)
    TextInputLayout tlRegisterPersonalCode;
    @BindView(R.id.tl_register_personal_info)
    TextInputLayout tlRegisterPersonalInfo;


    private String mCode="-1";
    private Context mContext;
    private final int CODE_TIME = 1000;
    private int codeNum = 60;
    private String businessId = "";
    private String codePhone = "";//获取验证码的手机号

    private Handler codeHandler = new Handler();
    private Runnable codeRunnable = new Runnable() {
        @Override
        public void run() {
            tvRegisterPersonalCode.setText("还剩" + codeNum + "秒");
            if (codeNum == 1) {
                tvRegisterPersonalCode.setText("获取");
                codeHandler.removeCallbacks(codeRunnable);
            } else {
                codeNum--;
                codeHandler.postDelayed(codeRunnable, CODE_TIME);
            }
        }
    };

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_register_personal;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    public static PersonalRegisterFragment newInstance() {
        return new PersonalRegisterFragment();
    }

    @Override
    public void init() {
        super.init();
        mContext = getActivity();
    }

    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        etRegisterPersonalPwdTrue.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                password();
            }
        });
        addListener(tlRegisterPersonalPhone, etRegisterPersonalPhone, "手机号不能为空");
        addListener(tlRegisterPersonalName, etRegisterPersonalName, "姓名不能为空");
        addListener(tlRegisterPersonalCode, etRegisterPersonalCode, "验证码不能为空");
        addListener(tlRegisterPersonalInfo, etRegisterPersonalInfo, "维护信息不能为空");

    }

    private void addListener(TextInputLayout textInputLayout, EditText editText, String str){
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                notNull(textInputLayout, editText, str);
            }
        });
    }

    private boolean notNull(TextInputLayout textInputLayout, EditText editText, String str) {
        if (TextUtils.isEmpty(editText.getText().toString().trim())) {
            textInputLayout.setError(str);
            return false;
        } else {
            textInputLayout.setError(null);
            textInputLayout.setErrorEnabled(false);

        }
        return true;
    }

    private boolean password() {
        if (etRegisterPersonalPwdTrue.getText().toString().length() >= etRegisterPersonalPwd.getText().toString().length() && !etRegisterPersonalPwdTrue.getText().toString().equals(etRegisterPersonalPwd.getText().toString())) {
            tlRegisterPersonalPwd.setError("密码不一致");
            return false;
        } else {
            tlRegisterPersonalPwd.setError(null);
            tlRegisterPersonalPwd.setErrorEnabled(false);

        }
        return true;
    }


    @OnClick({R.id.tv_register_personal_code, R.id.tv_register_personal_next, R.id.tv_register_personal_company})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_register_personal_code:
                if (tvRegisterPersonalCode.getText().toString().equals("获取")) {
                    if (UIUtils.isMobile(etRegisterPersonalPhone.getText().toString())) {
                        codeNum = 60;
                        codeHandler.postDelayed(codeRunnable, 1);
                        codePhone = etRegisterPersonalPhone.getText().toString();
                        getCodeHttp(etRegisterPersonalPhone.getText().toString());
                    } else {
                        ToastUtils.showShort(mContext, "请输入正确的手机号");
                    }
                }
                break;
            case R.id.tv_register_personal_next:
                if(!isNull()){
                    if(etRegisterPersonalCode.getText().toString().equals(mCode)){
                        if(etRegisterPersonalPwd.getText().toString().equals(etRegisterPersonalPwdTrue.getText().toString())){
                            if(etRegisterPersonalPwdTrue.getText().toString().trim().length()>=6){
                                if(codePhone.equals(etRegisterPersonalPhone.getText().toString().trim())){
                                    personalRegisterHttp();
                                }else{
                                    ToastUtils.showShort(mContext, "输入的手机号有误");
                                }
                            }else{
                                ToastUtils.showShort(mContext, "密码必须大于等于6位");
                            }
                        }else{
                            ToastUtils.showShort(mContext, "密码不一致");
                        }
                    }else{
                        ToastUtils.showShort(mContext, "验证码有误");
                    }
                }else{
                    ToastUtils.showShort(mContext, "请确认所有信息填写完毕");
                }
                break;
            case R.id.tv_register_personal_company:
                Intent it = new Intent(mContext, CompanyActivity.class);
                startActivityForResult(it, 110);
                break;
        }
    }

    private void personalRegisterHttp(){
        Map<String, String> map = new HashMap<>();
        map.put("businessId", businessId);
        map.put("maintainInfo", etRegisterPersonalInfo.getText().toString().trim());
        map.put("password", etRegisterPersonalPwdTrue.getText().toString().trim());
        map.put("phoneNumber", etRegisterPersonalPhone.getText().toString().trim());
        map.put("userName", etRegisterPersonalName.getText().toString().trim());
        map.put("verificationCode", etRegisterPersonalCode.getText().toString().trim());
//        String encrypt = RSAUtils.encrypt(RSAUtils.PUCLIC_KEY, new JSONObject(map).toString());
        String json =  new JSONObject(map).toString();
        ApiService.personalRegister(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {
                            LoginTipsDialog loginDialog = new LoginTipsDialog(mContext);
                            loginDialog.show();
                            loginDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    Intent it = new Intent(mContext, LoginActivity.class);
                                    it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(it);
                                }
                            });
                        } else{
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private boolean isNull(){
        if(!etRegisterPersonalPhone.getText().toString().equals("")&&!etRegisterPersonalPwd.getText().toString().equals("")&&
                !etRegisterPersonalPwdTrue.getText().toString().equals("")&&!etRegisterPersonalName.getText().toString().equals("")&&
                !etRegisterPersonalCode.getText().toString().equals("")&&
                !etRegisterPersonalInfo.getText().toString().equals("")&&!tvRegisterPersonalCompany.getText().toString().equals("")){
            return false;
        }
        return true;
    }

    private void getCodeHttp(String phone) {
        Map<String, String> map = new HashMap<>();
        map.put("phoneNumber", phone);
//        String encrypt = RSAUtils.encrypt(RSAUtils.PUCLIC_KEY, new JSONObject(map).toString());
        String json =  new JSONObject(map).toString();
        ApiService.getCode(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            mCode = retData.data;
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==110){
            boolean isCreate = data.getBooleanExtra("isCreate",false);
            if(isCreate){
                RegisterActivity mActivity = (RegisterActivity) mContext;
                mActivity.selectCompany();
            }else{
                String name = data.getStringExtra("name");
                businessId = data.getStringExtra("companyId");
                tvRegisterPersonalCompany.setText(name);
                tvRegisterPersonalCompany.setTextColor(Color.parseColor("#4D5576"));
            }
        }
    }
}